package com.siemens.industrial.app;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.siemens.industrial.model.admin.SystemConfig;
import org.quartz.*;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * Created by David on 2016/11/16.
 */
public enum DBBackupTask {
    INSTANCE;

    private JdbcTemplate jdbcTemplate;
    private static final String CONFIG_SQL = "SELECT * FROM `siemens`.`system_config` where `system_key` = 'DBBackup';";

    private static final String DB_JOB_KEY = "DBJob";
    private static final String DB_TRIGGER_KEY = "DBTrigger";
    private static final String DB_DIFF_JOB_KEY = "DBDiffJob";
    private static final String DB_DIFF_TRIGGER_KEY = "DBDiffTrigger";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    DBBackupTask() {
    }

    public DBBackupTask scheduler() throws SchedulerException, IOException {
        if (jdbcTemplate == null)
            jdbcTemplate = DBHelper.getJdbcTemplate();

        List<SystemConfig> systemConfigs = jdbcTemplate.query(CONFIG_SQL, SystemConfig.getRowMapper());
        SystemConfig systemConfig = systemConfigs.size() > 0 ? systemConfigs.get(0) : null;
        if (systemConfig == null || systemConfig.getSystemValue().isEmpty())
            return null;

        Scheduler scheduler = DaemonFactory.INSTANCE.getInstance();

        JobDetail detail = scheduler.getJobDetail(JobKey.jobKey(DB_JOB_KEY));
        JobDetail diffDetail = scheduler.getJobDetail(JobKey.jobKey(DB_DIFF_JOB_KEY));


        Map<String, Object> map = objectMapper.readValue(systemConfig.getSystemValue(), Map.class);
        if (map.size() <= 0) return null;

        String isEnable = map.get("isEnable").toString();
        if (isEnable.equals("false")) {
            scheduler.unscheduleJob(TriggerKey.triggerKey(DB_DIFF_TRIGGER_KEY));
            scheduler.unscheduleJob(TriggerKey.triggerKey(DB_TRIGGER_KEY));
            return null;
        }
        String timeType = ((Map) map.get("complete")).get("type").toString();
        List<Object> comList = (List<Object>) ((Map) map.get("complete")).get("value");
        String comValue = "";
        for (int i = 0; i < comList.size(); i++) {
            comValue = comValue + comList.get(i) + ",";
        }
        comValue = comValue.substring(0, comValue.length() - 1);
        String comTime = ((Map) map.get("complete")).get("time").toString();

        String comDate = "";
        if (timeType.equals("week")) {
            comDate = "0 0 " + comTime + " ? * " + comValue;
//            comDate = "0 * * ? * " + comValue;
        } else if (timeType.equals("month")) {
            comDate = "0 0 " + comTime + " " + comValue + " * ?";//"0 0 5 1,2,3 * ?"
//            comDate = "0 * * " + comValue + " * ?";
        }

        List<String> diffList = (List<String>) ((Map) map.get("differences")).get("value");
        if (diffList.size() > 0) {
            String diffTime = ((Map) map.get("differences")).get("time").toString();

            String diffValue = "";
            for (String value : diffList) {
                diffValue = diffValue + value + ",";
            }
            diffValue = diffValue.substring(0, diffValue.length() - 1);

            String diffDate = "0 0 " + diffTime + " ? * " + diffValue;
//            String diffDate = "0 * * ? * " + diffValue;

            if (diffDetail == null) {
                diffDetail = newJob(DBBackupDifferentialJob.class).withIdentity(DB_DIFF_JOB_KEY).build();
                Trigger diffTrigger = newTrigger().withIdentity(DB_DIFF_TRIGGER_KEY).forJob(diffDetail).withSchedule(CronScheduleBuilder.cronSchedule(diffDate)).build();
                scheduler.scheduleJob(diffDetail, diffTrigger);
            } else {
                Trigger newDiffT = newTrigger().withIdentity(DB_DIFF_TRIGGER_KEY).forJob(diffDetail).withSchedule(CronScheduleBuilder.cronSchedule(diffDate)).build();
                scheduler.rescheduleJob(TriggerKey.triggerKey(DB_DIFF_TRIGGER_KEY), newDiffT);
            }
        } else {
            scheduler.unscheduleJob(TriggerKey.triggerKey(DB_DIFF_TRIGGER_KEY));
        }


        if (detail == null) {
            detail = newJob(DBBackupJob.class).withIdentity(DB_JOB_KEY).build();
            Trigger dbTrigger = newTrigger().withIdentity(DB_TRIGGER_KEY).forJob(detail).withSchedule(CronScheduleBuilder.cronSchedule(comDate)).build();
            scheduler.scheduleJob(detail, dbTrigger);
        } else {
            Trigger newT = newTrigger().withIdentity(DB_TRIGGER_KEY).forJob(detail).withSchedule(CronScheduleBuilder.cronSchedule(comDate)).build();
            scheduler.rescheduleJob(TriggerKey.triggerKey(DB_TRIGGER_KEY), newT);
        }
        return null;
    }
}
